package com.example.matchandroiddevices.test;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class UsbDeviceDetector {
    private static final String TAG = "UsbDeviceDetector";

    private Context context;
    private UsbManager usbManager;
    private UsbPermissionListener permissionListener;
    private List<DeviceInfo> detectedDevices = new ArrayList<>();
    private UsbPermissionReceiver permissionReceiver;
    private BroadcastReceiver deviceReceiver;

    // 设备信息类
    public static class DeviceInfo {
        public UsbDevice device;
        public String name;
        public int vendorId;
        public int productId;
        public String description;
        public boolean hasPermission;

        @Override
        public String toString() {
            return String.format("%s (VID:0x%04X, PID:0x%04X) - %s [%s]",
                    name, vendorId, productId, description,
                    hasPermission ? "Permission granted" : "No permission");
        }
    }

    // 权限监听回调接口
    public interface UsbPermissionListener {
        void onPermissionGranted(UsbDevice device);
        void onPermissionDenied(UsbDevice device);
        void onDevicesDetected(List<DeviceInfo> devices);
    }

    public UsbDeviceDetector(Context context, UsbPermissionListener listener) {
        this.context = context;
        this.permissionListener = listener;
        this.usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);

        // 创建权限接收器
        permissionReceiver = new UsbPermissionReceiver(new UsbPermissionReceiver.UsbPermissionListener() {
            @Override
            public void onPermissionGranted(UsbDevice device) {
                if (permissionListener != null) {
                    permissionListener.onPermissionGranted(device);
                }
                refreshDeviceList(); // 刷新设备列表
            }

            @Override
            public void onPermissionDenied(UsbDevice device) {
                if (permissionListener != null) {
                    permissionListener.onPermissionDenied(device);
                }
                refreshDeviceList(); // 刷新设备列表
            }
        });

        // 注册接收器 - 添加 RECEIVER_NOT_EXPORTED 标志
        IntentFilter filter = new IntentFilter(UsbPermissionReceiver.getActionString());
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.registerReceiver(permissionReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
        }

        // 创建设备监听接收器
        deviceReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                    Log.d(TAG, "USB device attached");
                    refreshDeviceList();
                } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    Log.d(TAG, "USB device detached");
                    refreshDeviceList();
                }
            }
        };

        // 注册设备监听接收器 - 添加 RECEIVER_NOT_EXPORTED 标志
        IntentFilter deviceFilter = new IntentFilter();
        deviceFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        deviceFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        context.registerReceiver(deviceReceiver, deviceFilter, Context.RECEIVER_NOT_EXPORTED);
    }

    /**
     * 扫描并返回所有USB设备
     */
    public List<DeviceInfo> refreshDeviceList() {
        detectedDevices.clear();

        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        Log.d(TAG, "Found " + deviceList.size() + " USB devices");

        for (UsbDevice device : deviceList.values()) {
            DeviceInfo info = new DeviceInfo();
            info.device = device;
            info.name = device.getDeviceName();
            info.vendorId = device.getVendorId();
            info.productId = device.getProductId();
            info.description = getDeviceDescription(device);
            info.hasPermission = usbManager.hasPermission(device);

            detectedDevices.add(info);

            Log.d(TAG, "Device: " + info.toString());
        }

        // 通知监听器
        if (permissionListener != null) {
            permissionListener.onDevicesDetected(detectedDevices);
        }

        return detectedDevices;
    }

    /**
     * 获取设备描述
     */
    private String getDeviceDescription(UsbDevice device) {
        int vendorId = device.getVendorId();
        int productId = device.getProductId();

        // 识别常见USB串口芯片
        if (vendorId == 0x067B) return "Prolific USB-Serial";
        if (vendorId == 0x0403) return "FTDI USB-Serial";
        if (vendorId == 0x10C4) return "Silicon Labs CP210x";
        if (vendorId == 0x1A86) return "QinHeng CH340/CH341";
        if (vendorId == 0x0483) return "STM32 Virtual COM";

        // 可能的接口类型
        StringBuilder interfaces = new StringBuilder();
        int interfaceCount = device.getInterfaceCount();
        for (int i = 0; i < interfaceCount; i++) {
            interfaces.append("IF").append(i).append(":");
            interfaces.append(device.getInterface(i).getInterfaceClass());
            if (i < interfaceCount - 1) interfaces.append(", ");
        }

        return String.format("Unknown device (Interfaces: %s)", interfaces.toString());
    }

    /**
     * 请求设备权限 - 修复版本符合 Android 15 安全要求
     */
    public void requestPermission(UsbDevice device) {
        if (device != null) {
            if (usbManager.hasPermission(device)) {
                Log.d(TAG, "Already has permission for: " + device.getDeviceName());
                if (permissionListener != null) {
                    permissionListener.onPermissionGranted(device);
                }
            } else {
                Log.d(TAG, "Requesting permission for: " + device.getDeviceName());

                // 创建显式 Intent (而不是隐式)
                Intent explicitIntent = new Intent(UsbPermissionReceiver.getActionString());
                explicitIntent.setClass(context, UsbPermissionReceiver.class);

                // 对于 Android 12 及以上版本使用 FLAG_IMMUTABLE (而不是 FLAG_MUTABLE)
                int flags = PendingIntent.FLAG_IMMUTABLE;

                PendingIntent permissionIntent = PendingIntent.getBroadcast(
                        context, 0, explicitIntent, flags);

                usbManager.requestPermission(device, permissionIntent);
            }
        }
    }

    /**
     * 请求所有设备权限
     */
    public void requestPermissionForAll() {
        for (DeviceInfo info : detectedDevices) {
            if (!info.hasPermission) {
                requestPermission(info.device);
            }
        }
    }

    /**
     * 释放资源
     */
    public void release() {
        try {
            if (permissionReceiver != null) {
                context.unregisterReceiver(permissionReceiver);
            }
            if (deviceReceiver != null) {
                context.unregisterReceiver(deviceReceiver);
            }
        } catch (Exception e) {
            Log.e(TAG, "Error unregistering receiver", e);
        }
    }
}